/**
 * 页面调用示例
 * H5 和 APP示例
 * import wechatShare from '@/mixins/share'
 * wechatShare.call(this, params);
 */
import { shareDefault } from '@/config'
// #ifdef H5
import jweixin from 'jweixin-module'
import router from '@/router'
// 验证分享
function wxH5Share(params) {
    return new Promise(async (resolve, reject) => {
        if(!this){
            return reject({
                code: -1,
                msg: '请用『方法名』.call(this, params)来调用'
            })
        }

        let { authUrl, allowShare, title, summary, shareImg, jsApiList } = Object.assign({}, shareDefault, params);

        let baseUrl = router.$route.options.base; //二级域名
        baseUrl = window.location.origin + (baseUrl && baseUrl.substr(0, baseUrl.length - 1) || '');
        let currentHref = baseUrl + authUrl;

        let shareConfig = {
            title: title,//分享的title
            desc: summary,//分享的文案
            link: decodeURIComponent(allowShare ? currentHref : baseUrl),//分享点击后的跳转地址
            imgUrl: shareImg//分享图片
        };

        let res = await this.$http('wechatSign', {
            url: currentHref
        })

        jweixin.config({
            debug: true,
            appId: res.data.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
            timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            signature: res.data.signature, // 必填，签名，见附录1
            jsApiList: jsApiList
        });

        jweixin.ready(() => {
            // 分享设置
            jweixin.onMenuShareTimeline(shareConfig);
            jweixin.onMenuShareAppMessage(shareConfig);
        })
    })
}

export default wxH5Share
// #endif

// #ifdef APP-PLUS
function appShare(scene = 'WXSceneSession') {
    return new Promise(async (resolve, reject) => {

        if(!(this && this.shareParams)){
            return reject({
                code: -1,
                msg: '请用『方法名』.call(this, params)来调用'
            })
        }

        let { shareImg, path, webUrl, title, summary } = Object.assign({}, shareDefault, this.shareParams);

        uni.share({
            provider: 'weixin',
            scene: scene,
            type: 0,//0图文  5分享为小程序
            href: webUrl,
            title: title,
            summary: summary,
            imageUrl: shareImg,
            //分享为小程序
            // miniProgram: {
            //     id: 'gh_abcdefg',
            //     path: path,
            //     type: 0,
            //     webUrl: webUrl
            // },
            success: (res) => {
                console.log(JSON.stringify(res));
                resolve({
                    code: 0,
                    data: res
                })
            },
            fail:  (err) => {
                console.log("fail:" + JSON.stringify(err));
                reject({
                    code: -1,
                    data: err
                })
            }
        })
    });
}

export default appShare
// #endif
